package logic

import (
	"context"
	"fmt"
	"shopping-mall/models"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateProductLogic {
	return &UpdateProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateProductLogic) UpdateProduct(in *shopping_rpc.UpdateProductRequest) (*shopping_rpc.UpdateProductResponse, error) {
	// todo: add your logic here and delete this line
	var product models.Product
	if models.DB.Where("id = ?", in.ProductId).Limit(1).Find(&product).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if product.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if product.UserId != int(in.UserId) {
		return nil, fmt.Errorf("无权修改他人商品")
	}
	product = models.Product{
		Title:   in.Title,
		Price:   float64(in.Price),
		Image:   in.Image,
		ClassId: int(in.ClassId),
	}
	product.ID = uint(in.ProductId)
	if models.DB.Updates(&product).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &shopping_rpc.UpdateProductResponse{}, nil
}
